package com.ice.app.base.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import com.ice.app.system.auth.controller.AuthController;
import com.iceframework.core.entity.Result;
import com.iceframework.core.support.security.entity.IJWTInfo;
import com.iceframework.core.support.security.util.JwtUtils;
import com.iceframework.core.utils.WebUtils;

/**
 * 权限过滤拦截器
 * 
 * @author Palo
 *
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {

	protected final Log logger = LogFactory.getLog(getClass());

	@Autowired
	private AuthController authService;

	@Value("${web.ignore.startWith}")
	private String startWith;

	@Value("${web.jwt.token-header}")
	private String tokenHeader;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		request.setCharacterEncoding("UTF-8");
		HttpServletResponse resp = (HttpServletResponse) response;
		HttpServletRequest req = (HttpServletRequest) request;
		// 请请求为Method放行
		if (req.getMethod().equals(RequestMethod.OPTIONS.name())) {
			return true;
		}
		// 获得在下面代码中要用的request,response,session对象
		// 获得用户请求的URI
		String uri = req.getRequestURI().toString();
		// 不进行拦截的地址
		if (isStartWith(uri)) {
			return true;
		}
		IJWTInfo user = null;
		try {
			user = getJWTUser(false,req);
			if (user == null) {
				logger.debug("用户取Token过期:");
				WebUtils.responseOutWithJson(resp, Result.fail().setCode(Result.UNAUTHORIZED).setMsg("User Token Forbidden or Expired!"));
				return false;
			}
		} catch (Exception e) {
			logger.debug("用户取Token异常:" + e);
			WebUtils.responseOutWithJson(resp, Result.fail().setCode(Result.UNAUTHORIZED).setMsg("User Token Forbidden or Expired!"));
			return false;
		}
		return true;
	}

	/**
	 * 返回session中的用户信息
	 *
	 * @param request
	 * @param ctx
	 * @return
	 */
	private IJWTInfo getJWTUser(boolean checkToken,HttpServletRequest request) throws Exception {
		String authToken = null;
		authToken = request.getHeader(tokenHeader);
		if (StringUtils.isBlank(authToken)) {
			authToken = request.getParameter(tokenHeader);
			if (StringUtils.isBlank(authToken)) {
				authToken = (String) request.getAttribute(tokenHeader);
				if (StringUtils.isBlank(authToken)) {
					authToken = request.getParameter(tokenHeader);
				}
			}
		}

		// 发送登录日志
		boolean bool = authService.verify(authToken);
		if (bool || !checkToken) {
			return JwtUtils.getJWTInfoByToken(authToken);
		} else {
			return null;
		}
	}

	/**
	 * URI是否以什么打头
	 *
	 * @param requestUri
	 * @return
	 */
	private boolean isStartWith(String requestUri) {
		boolean flag = false;
		for (String s : startWith.split(",")) {
			if (requestUri.startsWith(s)) {
				return true;
			}
		}
		return flag;
	}

}
